#!/usr/bin/python3
import random
import unittest
import os

import repo_path

class MockOS (object):
  def __init__(self, files, cwd):
    self._files = files
    self._cwd = cwd

  def access(self, path, permission):
    return path in self._files

  def getcwd(self):
    return self._cwd

  def chdir(self, directory):
    self._cwd = os.path.join(self._cwd, directory)


class TestRepoPath(unittest.TestCase):
  def setUp(self):
    self.orig_access = repo_path.os.access
    self.orig_getcwd = repo_path.os.getcwd
    self.orig_chdir = repo_path.os.chdir
    files = set(['/tmp/repo_root/.build_config'])
    self.mock_os = MockOS(files,'/tmp/repo_root/test1/test2/test3')
    repo_path.os.access = self.mock_os.access
    repo_path.os.getcwd = self.mock_os.getcwd
    repo_path.os.chdir = self.mock_os.chdir

  def tearDown(self):
    repo_path.os.access = self.orig_access
    repo_path.os.getcwd = self.orig_getcwd
    repo_path.os.chdir = self.orig_chdir

  def test_find_root(self):
    """Tests that finding the root in a standard repo succeeds."""
    self.assertEqual(repo_path.find_root(),
                     ('/tmp/repo_root', 'test1/test2/test3'))
    repo_path.os.chdir('/tmp/repo_root/test1')
    self.assertEqual(repo_path.find_root(),
                     ('/tmp/repo_root', 'test1'))
    repo_path.os.chdir('/tmp/repo_root')
    self.assertEqual(repo_path.find_root(),
                     ('/tmp/repo_root', ''))

  def test_find_root_NoConfig(self):
    """Tests that no root file throws the correct exception."""
    repo_path.os.chdir('/tmp/repo_root2/test1')
    self.assertRaises(repo_path.RootMissingError, repo_path.find_root)


if __name__ == '__main__':
  unittest.main()
